<template>
  <div class="app-container">
    <Tabs value="actDetails" :animated="false" class="flex flex-1 flex-column">
      <TabPane label="活动明细" name="actDetails" class="flex flex-1 flex-column">
        <div class="app-content-container">
          <grid-table name="ActivityTable"
                      ref-form="searchForm"
                      :data="activityTableData"
                      :table-id="5"
                      :columns="columns"
                      :slot-column="slotColumns"
                      :perfect="false"
                      :loading.sync="loading"
                      :query="query"
                      @remote-method="getList">
            <template v-slot:form>
              <el-form :inline="true" size="small" label-width="80px">
                <el-row>
                  <el-form-item label="小程序">
                    <el-select v-model="query.appid">
                      <el-option v-for="item in $store.getters.user.maList" :key="item.id" :label="item.maName" :value="item.maId"/>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="活动日期">
                    <my-date-picker :value.sync="query.dateTimes" :default-value="query.dateTimes" />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="活动种类">
                    <el-select v-model="query.kindId" clearable>
                      <el-option v-for="item in global.kindItems" :key="item.kindId" :label="item.kindName" :value="item.kindId"/>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="活动类型">
                    <el-select v-model="query.actType" clearable>
                      <el-option-group v-for="item in global.kindItems" :key="item.kindId" :label="item.kindName">
                        <el-option v-for="child in item.children" :key="child.id" :label="`${child.name} [${child.prior}]`" :value="child.actType"/>
                      </el-option-group>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-row style="margin-bottom: -7px">
                  <el-form-item label="活动状态">
                    <el-radio-group v-model="query.status" @change="getList">
                      <el-radio>全部</el-radio>
                      <el-radio :label="0">待生效</el-radio>
                      <el-radio :label="1">进行中</el-radio>
                      <el-radio :label="2">已失效</el-radio>
                      <el-radio :label="3">已作废</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-row>
                <el-row class="mb5">
                  <el-form-item label=" ">
                    <Button type="success" @click="getList">查询</Button>
                    <el-dropdown class="ml0" trigger="click" @command="handleCreateCommand">
                      <Button type="primary" >创建活动<i class="ml0 el-icon-arrow-down el-icon--right"/></Button>
                      <el-dropdown-menu slot="dropdown">
                        <template v-for="item in global.kindItems">
                          <el-dropdown-item :key="child.name" :command="child" v-for="(child, index) in item.children" :divided="index === 0 && item.children.length > 1">{{child.name}}</el-dropdown-item>
                        </template>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-form-item>
                </el-row>
              </el-form>
            </template>
          </grid-table>
        </div>
      </TabPane>
      <TabPane label="活动汇总" name="actSummary">
      </TabPane>
    </Tabs>
    <!-- 创建活动窗口 -->
    <Modal v-if="actProp" :closable="false" :esc-closable="false" v-model="actModalShow" :styles="{zIndex: '60'}" footer-hide fullscreen>
      <div class="pl20 modal-content">
        <h3 class="bold" slot="header" style="text-align: center;">
          <span class="pb10" style="border-bottom: 4px solid #009688;">
            创建活动 - {{ modalTitle }}
          </span>
        </h3>
        <Form inline ref="actForm" :model="form" :rules="rules" :label-width="85" label-position="left">
          <Row class="pt20">
            <Col span="12">
              <Row>
                <FormItem label="选择门店" prop="shops">
                  <Transfer
                    :data="transferShopData"
                    :target-keys="form.shops"
                    filterable
                    :titles="['门店列表', '已选门店']"
                    :operations="['移除门店','选择门店']"
                    :list-style="listStyle"
                    @on-change="handleShopChange"
                    not-found-text="门店为空">
                  </Transfer>
                </FormItem>
              </Row>
              <Row>
                <FormItem label="活动描述" prop="actName">
                  <Input v-model="form.actName" :readonly="openMode === 'view'" placeholder="请简要描述活动" style="width: 400px"/>
                </FormItem>
              </Row>
              <Row>
                <FormItem label="活动时间">
                  <FormItem prop="beginTime">
                    <DatePicker v-model="form.beginTime" format="yyyy-MM-dd HH:mm" show-week-numbers type="datetime"
                                placeholder="活动开始时间" style="width: 150px" transfer
                    />
                  </FormItem>
                  <span class="mr10">至</span>
                  <FormItem prop="endTime">
                    <DatePicker v-model="form.endTime" format="yyyy-MM-dd HH:mm" show-week-numbers type="datetime"
                                placeholder="活动结束时间" style="width: 150px" transfer
                    />
                  </FormItem>
                </FormItem>
              </Row>
              <Row>
                <FormItem label="周期循环" prop="weeks">
                  <Checkbox :value="checkAll1"
                            :indeterminate="indeterminate1"
                            @click.prevent.native="handleCheckAll1">
                    全选
                  </Checkbox>
                  <CheckboxGroup v-model="form.weeks" style="display: inline-block" @on-change="checkAllChange1">
                    <Checkbox label="1">周一</Checkbox>
                    <Checkbox label="2">周二</Checkbox>
                    <Checkbox label="3">周三</Checkbox>
                    <Checkbox label="4">周四</Checkbox>
                    <Checkbox label="5">周五</Checkbox>
                    <Checkbox label="6">周六</Checkbox>
                    <Checkbox label="0">周日</Checkbox>
                  </CheckboxGroup>
                </FormItem>
              </Row>
              <Row>
                <FormItem label="活动对象" prop="userTypes">
                  <Checkbox :value="checkAll2"
                            :indeterminate="indeterminate2"
                            @click.prevent.native="handleCheckAll2">全选
                  </Checkbox>
                  <CheckboxGroup v-model="form.userTypes" style="display: inline-block" @on-change="checkAllChange2">
                    <Checkbox label="1">新用户</Checkbox>
                    <Checkbox label="2">普通用户</Checkbox>
                    <Checkbox label="3">会员</Checkbox>
                  </CheckboxGroup>
                </FormItem>
              </Row>
              <Row>
                <FormItem v-if="actProp.itemType && !actProp.itemType.hidden" label="促销范围" prop="itemType">
                  <RadioGroup v-model="form.itemType">
                    <Radio v-for="item in actProp.itemType.enums" :label="item.value">{{item.label}}</Radio>
<!--                    <Radio :label="0" :disabled="kindId != 3">全场</Radio>-->
<!--                    <Radio :label="1" :disabled="kindId == 3">限定品类</Radio>-->
<!--                    <Radio :label="2" :disabled="kindId == 3">限定SKU</Radio>-->
                  </RadioGroup>
                </FormItem>
              </Row>
            </Col>
            <Col span="12">
              <Row>
                <FormItem v-if="actProp.discountType && !actProp.discountType.hidden" label="计算结果" prop="discountType">
                  <RadioGroup v-model="form.discountType">
                    <Radio v-for="item in actProp.discountType.enums" :label="item.value">{{item.label}}</Radio>
                  </RadioGroup>
                </FormItem>
              </Row>
              <Row>
                <FormItem v-if="actProp.amount && !actProp.amount.hidden" label="满足条件" prop="amount">
                  <Input v-model="form.amount" number placeholder="请输入" style="width: 140px"/>
                </FormItem>
                <FormItem v-if="actProp.discount && !actProp.discount.hidden" label="优惠结果" prop="discount">
                  <Input v-model="form.discount" number placeholder="请输入" style="width: 140px" />
                </FormItem>
              </Row>
              <Row>
                <FormItem v-if="actProp.items && !actProp.items.hidden" style="width: 100%" prop="items" :label="form.itemType === 1 ? '活动品类':'活动商品'">
                  <vxe-grid
                    ref="xGrid"
                    auto-resize
                    border
                    header-align="center"
                    show-overflow
                    keep-source
                    height="540"
                    :mouse-config="{selected: true}"
                    :columns="importColumns"
                    :data="form.items"
                    :edit-rules="validCellRules"
                    :keyboard-config="{isArrow: true, isDel: true, isEnter: true, isTab: true, isEdit: true}"
                    :toolbar-config="tableToolbar"
                    :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
                  >
                    <template v-slot:bottom>
                      <Alert class="mt10" type="info" :closable="false" show-icon>合计 {{ form.items.length }} 项</Alert>
                    </template>
                    <template v-slot:toolbar_buttons>
                      <Row v-if="form.itemType === 1">
                        <Button class="mr10" type="success" @click="handleInputCategory">添加品类编码</Button>
                        <Button class="mr10" type="primary" @click="importCategoryFile">选择文件</Button>
                        <Button type="error" @click="handleClearAll">全部清空</Button>
                      </Row>
                      <Row v-else>
                        <Button class="mr10" type="success" @click="handleInputSku">添加商品编码</Button>
                        <Button class="mr10" type="primary" @click="importSkuFile">选择文件</Button>
                        <Button type="error" @click="handleClearAll">全部清空</Button>
                      </Row>
                    </template>
                  </vxe-grid>
                </FormItem>
              </Row>
            </Col>
          </Row>
        </Form>
        <div slot="footer" style="text-align: center">
          <Button class="mr20" style="width: 120px" @click="handleCancel">取消</Button>
          <Button v-if="openMode!='view'" type="primary" style="width: 120px" @click="handleCreate">确定</Button>
        </div>
      </div>
    </Modal>
    <Modal :closable="false" :mask-closable="false"
           :esc-closable="false" :title="form.itemType == 1 ? '批量添加品类':'批量添加商品'"
           v-model="itemModalShow" :styles="{zIndex:100}"
           footer-hide
    >
      <Input :rows="9" v-model="itemStr" type="textarea" :placeholder="form.itemType == 1 ? '请输入品类编码，多个品类之间用逗号分开...':'请输入商品编码，多个商品之间用逗号分开...'"></Input>
      <div class="mt10" style="text-align: right">
        <Button @click="handleImportCancel" :disabled="importLoading">取消</Button>
        <Button class="ml10" type="primary" @click="handleImportCode" :loading="importLoading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="errModalShow" title="导入结果" transfer :styles="{overflow:'scroll'}">
      <div v-for="item in errData">
        {{item}} 编码不存在
      </div>
    </Modal>
  </div>
</template>

<script>
  import request from '@/utils/request'
  import GridTable from '@/components/GridTable/index'
  import DatePicker from '@/components/DatePicker/index'
  import ModalItemList from '@/components/ModalItemList/index'
  import XLSX from 'xlsx'
  export default {
    name: 'Activity',
    components: {
      GridTable,
      ModalItemList,
      'my-date-picker': DatePicker
    },
    data() {
      return {
        global: {
          actTypeItems: [],
          actTypeDict: {},
          kindItems: [],
          shops: [],
          weeks: ['0','1','2','3','4','5','6'],
          userTypes: ['0','1','2','3'],
          discountTypes: [],
        },
        tableToolbar: {
          slots: {
            buttons: 'toolbar_buttons'
          }
        },
        validCellRules: {
          discount: [
            { required: true, message: '请输入优惠结果' }
          ],
          discountType: [
            { required: true, message: '请选择优惠方式' }
          ],
          amount: [
            { required: true, message: '请输入数量' }
          ]
        },
        importColumns: [
          { type: 'seq', title: '序号', width: 80, align: 'center' },
          { field: 'code', title: '编码', width: 120, align: 'center' },
          { field: 'name', title: '名称', width: 'auto', headerAlign: 'center' },
          { field: 'discountType', title: '优惠方式', width: 120, align: 'center', visible: true, editRender: { name: 'Select', options: [] } },
          { field: 'discount', title: '优惠结果', width: 120, align: 'center', visible: true, editRender: { name: 'Input', autoselect: true } },
          { field: 'amount', title: '数量', width: 120, align: 'center', visible: false, editRender: { name: 'InputNumber', props: { min: 1} } },
          { title: '操作', width: '80', align:'center', slots: {
              default: ({ row }) => {
                return [
                  <vxe-button type="text" nativeOnClick={ () => { this.handleDeleteImport(row) } }>删除</vxe-button>
                ]
              }
            }
          }
        ],
        errData: [],
        errModalShow: false,
        transferShopData: [],
        activityTableData: [],
        loading: false,
        importLoading: false,
        showTime: false,
        indeterminate1: true,
        indeterminate2: true,
        checkAll1: false,
        checkAll2: false,
        kindId: undefined,
        openMode: 'create',
        query: {
          status: undefined,
          dateTimes: [],
          kindId: undefined,
          actType: undefined,
          appid: undefined,
          itemType: undefined,
          pageNum: 1,
          pageSize: 10,
          total: 0
        },
        form: {
          actName: undefined,
          shops: [],
          beginTime: undefined,
          endTime: undefined,
          userTypes: [],
          weeks: [],
          days: [],
          discount: undefined,
          itemType: 0,
          discountType: '0',
          items: [],
          amount: undefined,
          status: 0,
          actType: undefined
        },
        rules: {
          actName: [ { required: true, message: '请输入活动名称', trigger: 'change'} ],
          beginTime: [ { required: true , type: 'date', message: '请输入活动开始时间', trigger: 'change'} ],
          endTime: [ { required: true , type: 'date', message: '请输入活动结束时间', trigger: 'change'} ],
          shops: [{ required: true, type: 'array', message: '请选择活动门店', trigger: 'change', min: 1}],
          weeks: [{ required: true, type: 'array', message: '请选择周期天数', trigger: 'change', min: 1}],
          items: [{ required: true, type: 'array', message: '品类或商品不能为空', trigger: 'change', min: 1}],
          userTypes: [{ required: true, type: 'array', message: '请选择活动对象', trigger: 'change', min: 1}],
          amount: [
            { required: true, type: 'number', message: '请输入满足条件', trigger: 'change' },
            { type: 'number', required: true, message: '满足条件必须大于0', trigger: 'change', min: 0.0000001 }
          ],
          discount: [
            { type: 'number', required: true, message: '请输入优惠结果', trigger: 'change' },
            { type: 'number', required: true, message: '优惠结果必须大于0', trigger: 'change', min: 0.0000001 },
            { type: 'number', required: true, message: '折扣不能大于等于100', trigger: 'change',
              validator: (rule, value) => {
                return this.form.discountType != '1' || (this.form.discountType=='1'&&value<100)
              }
            }
          ]
        },
        itemStr: '',
        importOk: false,
        temp: {},
        actProp: {},
        modalTitle: '',
        actModalShow: false,
        itemModalShow: false,
        listStyle: {
          width: '200px',
          height: '320px'
        },
        columns: [
          { title: '操作', align: 'center', width: 200,
            slots: {
              default: ({ row }) => {
                return [
                  <el-button type='text' nativeOnClick={ () => { this.handleViewDetails(row) } }>详情</el-button>,
                  <el-button type="text" nativeOnClick={ () => { this.handleUpdate(row, 0) } }>失效</el-button>,
                  <el-button type="text" nativeOnClick={ () => { this.handleUpdate(row, 1) } }>生效</el-button>,
                  <el-button type='text' nativeOnClick={ () => { this.handleUpdate(row, 3) } } >作废</el-button>
                ]
              }
            }
          }
        ],
        slotColumns: {
          statusLabel: {
            default: ({ row }) => {
              return [
                <Tag color={row.status==1?'success':row.status==2?'warning':row.status==3?'error':'default'}>{row.statusLabel}</Tag>
              ]
            }
          },
          actTimes: {
            default: ({ row }) => {
              return [
                <span>{row.beginTime} 至 {row.endTime}</span>
              ]
            }
          }
        }
      }
    },
    created() {
      // 初始化初始数据
      this.initData()
      // 加载远程初始数据
      this.loadData()
      request.$bus.$on('closeLoading',() =>{
        this.loading = false
      })
      this.getList()
    },
    methods: {
      initData() {
        this.query.appid = this.$store.getters.user.maList[0].maId
        const end = this.getDayEnd()
        const start = this.getDayStart()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.query.dateTimes = [start, end]
        this.itemStr = ''
      },
      loadData() {
        request({
          url: '/mall/activity/kind/list',
          method: 'get',
          headers: {
            appid: this.query.appid
          }
        }).then(res => {
          this.global.kindItems = res.rows
          this.$nextTick(() => {
            this.global.kindItems.forEach((kind) => {
              kind.children.forEach((typeItem) => {
                this.global.actTypeDict[typeItem.actType] = typeItem
              })
            })
          })
        })
        request({
          url: '/mall/shop/list',
          method: 'get',
          headers: {
            appid: this.query.appid
          }
        }).then(res => {
          this.global.shops = res.rows
          this.transferShopData = this.global.shops.map((item) => {
            return {
              key: item.id,
              label: item.name
            }
          })
        })
        request({
          url: '/mall/dictionary',
          method: 'get',
          params: {
            parentId: 10
          },
          headers: {
            appid: this.query.appid
          }
        }).then(res => {
          this.global.discountTypes = res.data
          this.importColumns[3].editRender.options = this.global.discountTypes
        })
      },
      handleDeleteImport(row) {
        this.confirm('确定要删除数据？', '提示')
            .then(type => {
              if (type === 'confirm') {
                this.$refs.xGrid.remove(row)
              }
            })
      },
      handleClearAll() {
        if (this.form.items.length > 0) {
          this.confirm('是否要清空所有活动商品？', '提示')
            .then(type => {
              if (type === 'confirm') {
                this.form.items = []
              }
            })
        }
      },
      checkDifferent() {
        let diff = false
        this._.forEach(this.temp, (value, key) => {
          if (diff) return
          if (Array.isArray(value)) {
            let diffItems = this._.difference(value, this.form[key])
            diff = diffItems.length > 0
          } else {
            diff = this.form[key] != value
          }
        })
        return diff
      },
      createTemp() {
        this.temp = {
          actName: undefined,
          shops: [],
          beginTime: undefined,
          endTime: undefined,
          userTypes: [],
          weeks: [],
          days: [],
          discount: undefined,
          itemType: 0,
          discountType: '0',
          items: [],
          amount: undefined,
          status: 0,
          actType: undefined
        }
      },
      getList() {
        this.loading = true
        request({
          url: '/mall/activity/list',
          method: 'post',
          headers: {
            appid: this.query.appid
          },
          data: this.query
        }).then(res => {
          this.activityTableData = res.rows;
          this.loading = false
          this.query.total = res.total
        }).catch(res => {
          this.errMsg(res.msg)
          this.loading = false
        })
      },
      handleViewDetails(row) {
        const request1 = request({
          url: '/mall/activity/'+row.id,
          method: 'get',
          headers: {
            appid: this.query.appid
          }
        }).then(res => {
          this.form = res.data
          this.actProp = this.global.actTypeDict[this.form.actType].props
          if (!this.actProp.itemType.hidden) {
            this.form.itemType = this.actProp.itemType.enums[0].value
          }
          if (!this.actProp.discountType.hidden) {
            this.form.discountType = this.actProp.discountType.enums[0].value
          }
          this.actModalShow = true
          this.openMode = 'view'
        })
      },
      handleUpdate(row, status) {
        console.log(row)
        if (row.status != 3 && status == 3) {
          this.confirm('是否要作废活动？', '提示')
            .then(type => {
              if (type == 'confirm') {
                request({
                  url: '/mall/activity/update',
                  method: 'post',
                  data: {
                    status: status,
                    id: row.id,
                  },
                  headers: {
                    appid: this.query.appid
                  }
                }).then(res => {
                  if (res.code == 200) {
                    this.getList()
                    this.msgSuccess('活动作废成功')
                  }
                })
              }
            })
        } else if (row.status == 0 && row.status != 3 && status == 1) {
          if (row.endTime < new Date()) {
            return this.msgError("活动结束日期小于当前日期，无法生效！")
          }
          this.confirm('确认活动立刻生效？', '提示')
            .then(type => {
              if (type == 'confirm') {
                request({
                  url: '/mall/activity/update',
                  method: 'post',
                  data: {
                    status: status,
                    id: row.id,
                  },
                  headers: {
                    appid: this.query.appid
                  }
                }).then(res => {
                  if (res.code == 200) {
                    this.getList()
                    this.msgSuccess('活动已生效')
                  }
                })
              }
            })
        }
      },
      handleCancel() {
        // console.log(this.checkDifferent())
        // if (this.checkDifferent()) {
        //   this.confirm('修改内容尚未保存，是否确认退出？','退出提示')
        //       .then(type => {
        //         console.log(type)
        //         if (type == 'confirm') {
        //           this.actModalShow = false
        //           this.$refs.actForm.resetFields()
        //         }
        //       })
        // } else {
          this.actModalShow = false
          this.$refs.actForm.resetFields()
        // }
      },
      handleCreate() {
        this.$refs.actForm.validate((valid) => {
          if (valid) {
            request({
              url: '/mall/activity/save',
              method: 'post',
              data: this.form,
              headers: {
                appid: this.query.appid
              }
            }).then(res => {
              this.msgSuccess("保存成功")
              this.actModalShow = false
              this.$refs.actForm.resetFields()
              this.getList()
            }).catch(res => {
              this.msgError(res.msg)
            })
          } else {
            this.$Message.error('活动表单填写不正确！请检查后再提交！');
          }
        })
      },
      handleShopChange(newKeys, direction, moveKeys) {
        console.log(newKeys, direction, moveKeys)
        this.form.shops = newKeys
      },
      handleCreateCommand(cmd) {
        this.importOk = false
        this.modalTitle = cmd.name
        this.createTemp()
        this.temp.weeks = this.global.weeks
        this.temp.userTypes = this.global.userTypes
        this.temp.actType = cmd.actType
        this.kindId = cmd.kindId
        if (this.kindId !== 3) {
          this.temp.itemType = 1
        }
        this.form = this._.cloneDeep(this.temp)
        request({
          url: '/mall/activity/type/'+cmd.id,
          method: 'get',
          headers: {
            appid: this.query.appid
          }
        }).then(res => {
          this.actProp = res.data.props
          if (!this.actProp.itemType.hidden) {
            this.form.itemType = this.actProp.itemType.enums[0].value
          }
          if (!this.actProp.discountType.hidden) {
            this.form.discountType = this.actProp.discountType.enums[0].value
          }
          const columns = this.$refs.xGrid ? this.$refs.xGrid.getTableColumn().fullColumn : this.importColumns
          if (columns) {
            switch (Number(cmd.id)) {
              // 全场满赠
              case 2: {
                columns[3].visible = false
                columns[4].visible = false
                columns[5].visible = true
                break
              }
              // 第N件优惠
              case 4: {
                columns[3].visible = true
                columns[4].visible = true
                columns[5].visible = true
                columns[5].title = "第N件优惠"
                break
              }
              // X元N件
              case 8: {
                columns[3].visible = true
                columns[4].visible = true
                columns[5].visible = true
                columns[5].title = "N件"
                break
              }
              // 部分满减
              case 11: {
                columns[3].visible = true
                columns[4].visible = true
                columns[5].visible = true
                columns[5].title = "满足条件"
                break
              }
              // 单品折扣
              case 3: {
                columns[3].visible = true
                columns[4].visible = true
                columns[5].visible = false
                break
              }
              default: break
            }
          }
          if (this.$refs.xGrid) {
            this.$refs.xGrid.reloadColumn(columns)
          }

          this.actModalShow = true
          this.openMode = 'create'

        }).catch((res) => {
          this.actProp = {}
          this.msgError(res.msg)
        })
      },
      checkAllChange1(data) {
        if (data.length === this.global.weeks.length) {
          this.indeterminate1 = false;
          this.checkAll1 = true;
        } else if (data.length > 0) {
          this.indeterminate1 = true;
          this.checkAll1 = false;
        } else {
          this.indeterminate1 = false;
          this.checkAll1 = false;
        }
      },
      checkAllChange2(data) {
        if (data.length === this.global.userTypes.length) {
          this.indeterminate2 = false;
          this.checkAll2 = true;
        } else if (data.length > 0) {
          this.indeterminate2 = true;
          this.checkAll2 = false;
        } else {
          this.indeterminate2 = false;
          this.checkAll2 = false;
        }
      },
      handleCheckAll1() {
        if (this.indeterminate1) {
          this.checkAll1 = false
        } else {
          this.checkAll1 = !this.checkAll1
        }
        this.indeterminate1 = false

        if (this.checkAll1) {
          this.form.weeks = this._.cloneDeep(this.global.weeks)
        } else {
          this.form.weeks = [];
        }
      },
      handleCheckAll2() {
        if (this.indeterminate2) {
          this.checkAll2 = false
        } else {
          this.checkAll2 = !this.checkAll2
        }
        this.indeterminate2 = false;

        if (this.checkAll2) {
          this.form.userTypes = this._.cloneDeep(this.global.userTypes)
        } else {
          this.form.userTypes = [];
        }
      },
      handleInputCategory() {
        this.itemModalShow = true
      },
      handleInputSku() {
        this.itemModalShow = true
      },
      handleImportCancel() {
        this.itemModalShow = false
        this.importLoading = false
      },
      handleImportCode() {
        if (!this.itemStr) {
          return this.msgError("品类或商品不能为空")
        }
        let importItems = this.itemStr.split(',')
        // 检查编码是否已经存在
        let findResult = this._.find(this.form.items, (item) => { return importItems.indexOf(item.code) >= 0 })
        if (findResult) {
          return this.msgError(`编码 ${findResult.code} 已经存在！`)
        }
        this.importLoading = true
        request({
          url: '/mall/activity/importCode',
          method: 'post',
          data: {
            items: importItems,
            itemType: this.form.itemType
          },
          headers: {
            appid: this.query.appid
          }
        }).then(res => {
          this.importLoading = false
          this.itemModalShow = false
          console.debug(this.form)
          this.form.items = this.form.items.concat(res.data.map((item) => {
            return {
              id: item.id,
              code: item.code||item.categoryCode,
              name: item.name||item.categoryName
            }
          }))
          this.itemStr = ''
          this.msgSuccess('导入成功')
        }).catch(res => {
          this.importLoading = false
          this.msgError('编码不存在：' + res.data.join(', '))
        })
      },
      importCategoryFile() {
        this.$refs.xGrid.readFile({
          types: ['xls', 'xlsx']
        }).then(params => {
          console.log(params)
          const { files } = params.target
          const fileReader = new FileReader()
          fileReader.onload = (ev) => {
            const data = ev.target.result
            const workbook = XLSX.read(data, { type: 'binary' })
            let workSheet = workbook.Sheets[workbook.SheetNames[0]]
            const jsonData = XLSX.utils.sheet_to_json(workSheet)
            // 转化数据并且检查数据是否合法
            const tableData = {}
            jsonData.forEach((item) => {
              tableData[item['品类编码']||item['编码']] = {
                code: item['品类编码']||item['编码'],
                discount: item['优惠结果'],
                discountType: item['优惠方式'],
                amount: item['数量']
              }
            })
            request({
              url: '/mall/activity/importCode',
              method: 'post',
              data: {
                items: jsonData.map((item) => item['品类编码']||item['编码']),
                itemType: this.form.itemType
              },
              headers: {
                appid: this.query.appid
              }
            }).then(res => {
              this.form.items = res.data.map((item) => {
                return {
                  id: item.id,
                  code: item.code,
                  name: item.name,
                  discount: tableData[item.code].discount,
                  discountType: tableData[item.code].discountType,
                  amount: tableData[item.code].amount||1
                }
              })
            }).catch(res => {
              this.errData = res.data
              this.errModalShow = true
            })
          }
          fileReader.readAsBinaryString(files[0])
        })
      },
      importSkuFile() {
        this.$refs.xGrid.readFile({
          types: ['xls', 'xlsx']
        }).then(params => {
          const { files } = params.target
          const fileReader = new FileReader()
          fileReader.onload = (ev) => {
            const data = ev.target.result
            const workbook = XLSX.read(data, { type: 'binary' })
            let workSheet = workbook.Sheets[workbook.SheetNames[0]]
            const jsonData = XLSX.utils.sheet_to_json(workSheet)
            // 转化数据并且检查数据是否合法
            const tableData = {}
            jsonData.forEach((item) => {
              tableData[item['商品编码']||item['编码']] = {
                code: item['商品编码']||item['编码'],
                discount: item['优惠结果'],
                discountType: item['优惠方式']+'',
                amount: item['数量']
              }
            })
            // 解析数据
            request({
              url: '/mall/activity/importCode',
              method: 'post',
              data: {
                items: jsonData.map((item) => item['商品编码']||item['编码']),
                itemType: this.form.itemType
              },
              headers: {
                appid: this.query.appid
              }
            }).then(res => {
              this.form.items = res.data.map((item) => {
                return {
                  id: item.id,
                  code: item.code,
                  name: item.name,
                  discount: tableData[item.code].discount,
                  discountType: tableData[item.code].discountType,
                  amount: tableData[item.code].amount||1
                }
              })
            }).catch(res => {
              this.errData = res.data
              this.errModalShow = true
            })
            // this.itemStr = this.itemStr.trim()
            // const reg=/,$/gi
            // this.itemStr = this.itemStr.replace(reg, '')
          }
          fileReader.readAsBinaryString(files[0])
        })
      }
    }
  }
</script>

<style>
  .el-tabs__header.is-left {
    width: 150px;
  }
  .el-dropdown {
    vertical-align: top;
  }
  .el-dropdown + .el-dropdown {
    margin-left: 15px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .modal-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin: 0 120px;
    height: 100%;
  }
  .tag-container {
    height: 200px;
    overflow-y: auto;
  }
  .ivu-tabs-content{
    flex: 1;
    display: flex;
  }
  .custom-grid-row {
    height: auto;
  }
  .custom-grid-cell {
    height: auto;
  }
</style>
